package com.zenithmind.gateway.route;

import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.Builder;
import org.springframework.cloud.gateway.route.builder.GatewayFilterSpec;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 通信相关服务路由配置器
 * 专门负责聊天服务、AI聊天服务的路由配置
 * 遵循单一职责原则：只负责通信相关的路由配置
 */
@Slf4j
@Component
public class CommunicationRouteConfigurer implements RouteConfigurer {

    @Override
    public void configureRoutes(Builder routes) {
        log.info("配置通信相关服务路由...");
        
        // 聊天服务路由 - 消息、聊天室、用户
        routes.route("chat-service-route", r -> r
            .path("/api/chat/**",
                 "/api/zenithMind/chat/**",
                 "/api/zenithMind/message/**",
                 "/api/zenithMind/room/**")
            // 仅为纯/api/前缀的路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiPrefix(f, "/api/chat"))
            .uri("lb://chat-service"));
            
        // AI聊天服务路由 - AI对话、模型配置
        routes.route("ai-chat-service-route", r -> r
            .path("/api/zenithMind/aiChat/**", 
                 "/api/zenithMind/modelConfig/**",
                 "/api/zenithMind/api/v1/ai/**",
                 "/api/zenithMind/api/v1/model/**")
            // 仅为API v1路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiV1(f, "/api/zenithMind/api/v1/"))
            .uri("lb://ai-chat-service"));
    }

    @Override
    public String getConfigureName() {
        return "CommunicationRouteConfigurer";
    }

    @Override
    public int getOrder() {
        return 5;
    }
    
    /**
     * 路径过滤器工具方法 - 专用于/api/zenithMind/api/v1/前缀的路径
     * 如果路径以指定前缀开头，则移除前缀
     */
    private GatewayFilterSpec pathFilterForApiV1(GatewayFilterSpec f, String prefixPattern) {
        return f.rewritePath("/api/zenithMind/api/v1/(?<segment>.*)", "/api/zenithMind/${segment}");
    }
    
    /**
     * 路径过滤器工具方法 - 专用于/api/前缀的路径
     * 如果路径以指定前缀开头，则移除前缀
     */
    private GatewayFilterSpec pathFilterForApiPrefix(GatewayFilterSpec f, String prefixPattern) {
        return f.rewritePath("/api/(?<segment>.*)", "/${segment}");
    }
}
